package api

import (
	"ams/dao"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"lib/http"
	"lib/id"
	"lib/structs/ams"
	"lib/structs/tables"
	"time"
)

var PolicyApi = new(policyApi)

type policyApi struct {
}

func (a policyApi) List(c *gin.Context) {
	var in ams.SearchPolicyDto
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	li, err := dao.PolicyDao.FindListByName(in)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.Ok(c, li)
}

func (a policyApi) Add(c *gin.Context) {
	var in ams.AddPolicyDto
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	var m tables.AmsPolicy
	_ = copier.Copy(&m, in)
	m.Id = id.GetSnowId()
	m.CreatedAt = time.Now().Unix()
	err := dao.PolicyDao.Create(&m)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	err = dao.Cache.LoadAmsPolicy()
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}

func (a policyApi) Update(c *gin.Context) {
	var in ams.UpdatePolicyDto
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	var (
		m   tables.AmsPolicy
		err error
	)
	m, err = dao.PolicyDao.FindById(in.Id)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	_ = copier.Copy(&m, in)
	err = dao.PolicyDao.Update(m)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	err = dao.Cache.LoadAmsPolicy()
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}

func (a policyApi) Delete(c *gin.Context) {
	in := struct {
		Id int64 `form:"id"`
	}{}
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	err := dao.PolicyDao.Delete(in.Id)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	err = dao.Cache.LoadAmsPolicy()
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}
